11 / 12

Can you change the access modifier of a base class method in a derived class? (Hiding vs Overriding)

Difficulty: 3/10

Access Modifiers, Overriding and Hiding

Generally, a derived class cannot override a base method with a more restrictive access level because that would violate substitutability. For example, a public base method cannot normally become protected or private in an override. Languages have specific rules around increasing visibility, method hiding and overriding. Hiding creates a new member in the derived class rather than participating in runtime polymorphism, so it should be used deliberately and not as a substitute for proper overriding.

javascript
  1. 1

    An override normally preserves the accessibility contract of the base method.

  2. 2

    Reducing visibility would prevent valid base-type usage.

  3. 3

    Overriding participates in polymorphic dispatch.

  4. 4

    Hiding/shadowing creates a separate member in the derived type.

  5. 5

    Exact access-modifier rules vary between languages.

Follow-up Questions

  • What is method hiding?
  • What is runtime polymorphism?
  • Why can't an override reduce visibility?
  • How does C# new keyword differ from override?
Share

Share via WhatsApp, X, Facebook, LinkedIn or copy link. Open Graph preview enabled.